<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Contact_Model extends MY_Model {
    private $entity_name = 'Contact_Entity';

    public function __construct()
    {
        parent::__construct();
        $this->load->model('entity/contact_entity', $this->entity_name);
    }

    public function save($contact)
    {
        $contact['created_at'] = get_current_date();
        $this->db->trans_begin();
        $this->db->insert($this->table_contact_name, $contact);
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }

    public function changeStatus($id, $contact){
        $this->db->trans_begin();
        $this->db->where('id', $id);
        $this->db->update($this->table_contact_name, $contact);
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }

    public function countContact($user_id, $option=array()){
        $this->db->select('a.id', true);
        $this->db->from($this->table_contact_name . ' a');
        $this->db->where('a.user_id', $user_id);
        if(count($option)>0){
            $this->db->where($option);
        } else {
            $this->db->where(array('a.deleted_at' => null));
        }
        return $this->db->count_all_results();
    }

    public function paging($user_id, $limit=CONTACT_LIMIT, $offset=0, $aSelect=array(), $option=array()){
        $select = "";
        if(count($aSelect)>0){
            $select = implode(',', $aSelect);
        } else {
            $select = "a.id, a.name, a.email, a.subject, a.message, a.unread, a.created_at, a.deleted_at";
        }
        $this->db->select($select, true);
        $this->db->from($this->table_contact_name . ' a');
        $this->db->where('a.user_id', $user_id);
        if(count($option)>0){
            $this->db->where($option);
        } else {
            $this->db->where(array('a.deleted_at' => null));
        }
        $this->db->order_by('a.created_at', 'DESC');
        $this->db->limit($limit, $offset);
        $result = $this->db->get()->result($this->entity_name);
        return $result;
    }

    public function get($id){
        $select = "a.id, a.name, a.email, a.subject, a.message, a.unread, a.created_at, a.deleted_at";
        $this->db->select($select, true);
        $this->db->from($this->table_contact_name . ' a');
        $this->db->where('a.id', $id);
        $result = $this->db->get()->first_row($this->entity_name);
        return $result;
    }
}
?>